# Defining general cleaning function (used in 01)

to_clean_elec_data <- function(df) {
    df %>%
        filter(!is.na(land)) %>%
        mutate(across(4:ncol(.), as.numeric)) %>%
        pivot_longer(
            cols = c(8:ncol(.)),
            names_to = "party",
            values_to = "votes"
        ) 
}

# Projecting historical boundaries function (used in 02)

fit_into_hist_borders <- function(df, ags_lim) {
    df %>% 
        filter(year == "2017" & as.numeric(ags) < ags_lim) %>% 
        select(year, gen, ags, geometry) %>%
        rename(c("year_proj" = "year", "ags_proj"= "ags", "gen_proj" = "gen")) %>% 
        st_sf()
}


# Simple proportions function (used in 02)

calc_prop <- function(col_1, col_2) {
    x <- col_1
    y <- col_2
    prop <- x/y
}


# Custom function to read and filter ARDECO covariate CSVs
read_ger_dat <- function(file, nuts_vers = 2016, nuts_level = 3) {
    dat <- read_csv(file)
    var_name <- str_extract(file, "(?<=ARDECO\\-).*(?=.csv$)")
    
    dat <- dat %>% 
        janitor::clean_names() %>% 
        mutate(ctry = str_sub(territory_id, end = 2L)) %>% 
        filter(versions == nuts_vers & level_id == nuts_level & ctry == "DE" & unit %in% c("PPS", "Thousands Persons", "Persons", "Percent", "Million EUR")) 
    
    names(dat)[names(dat) == "value"] <- paste(tolower(var_name), unique(dat$unit), sep = "_")
    
    dat <- dat %>%
        janitor::clean_names() %>% 
        select(-c("versions", "level_id", "ctry", "unit"))
    
    return(dat)
}
